from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split,GridSearchCV
import sklearn.neighbors as neig

# 1.获取数据集
iris = load_iris()
# 数据集特征名称
print(iris.feature_names)
# 2.数据预处理
# 2.1 数据分割
x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target,test_size=0.3,random_state=2)
# 2.2 标准化
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.fit_transform(x_test)
# 3.模型训练
# 3.1 实例化分类器
estimator = neig.KNeighborsClassifier(n_neighbors=9)

# 3.2 使用交叉验证网格搜索
# estimator-->分类器
# param_grid-->指定的数据
params_grid = {"n_neighbors":[1,3,5,7,9,11]}
estimator = GridSearchCV(estimator,param_grid=params_grid,cv=5)

# 3.3 模型训练
estimator.fit(x_train,y_train)
# 4.模型评估
# 4.1 传入测试集数据 预测出来的结果跟实际的测试集结果和真实结果
y_pre = estimator.predict(x_test)
print(y_pre)
print(y_test)
# 4.2 输出准确率 注意：X-->测试集特征 y-->测试集真实结果
ret = estimator.score(x_test,y_test)
print("准确率：",ret)

print('最好的模型：',estimator.best_estimator_)
print('最好的得分：',estimator.best_score_)
print('最好的结果：',estimator.cv_results_)
